﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ScrollCenterController : MonoBehaviour{


    ScrollRect sr;
    Scrollbar sb;

    void Start()
    {
        sr = GetComponent<ScrollRect>();
        sb = sr.horizontalScrollbar;
        UIDragListener.RectEndHanler(sr.gameObject, (d)=> { OnEndDrag(d,false); });
        UIDragListener.RectEndHanler(sb.gameObject, (d) => { OnEndDrag(d, true); });
    }

    float progress = 0;
    float centerValue = 0;
    
    void OnEndDrag(PointerEventData eventData,bool isNeedFlipDir)
    {
        int moveDir = (eventData.position.x - eventData.pressPosition.x) > 0 ? 1 : -1;
        float localPosContenNeedTo = sr.content.GetComponent<RectTransform>().anchoredPosition.x;
        Transform childItem = sr.content.GetChild(0);
        RectTransform rectTr = childItem.GetComponent<RectTransform>();
        if (isNeedFlipDir)
        {
            moveDir *= -1;
        }
        if (moveDir > 0)
        {
            for (int i = 1; i <= sr.content.childCount; i++)
            {
                float curDist = -(i-1) * (rectTr.sizeDelta.x + sr.content.GetComponent<HorizontalLayoutGroup>().spacing);
                float abs = Mathf.Abs(localPosContenNeedTo-curDist);
                if (abs< rectTr.sizeDelta.x)
                {
                    centerValue = curDist;
                    break;
                }
            }
            localPosContenNeedTo = Mathf.Min(0, localPosContenNeedTo);
        }
        else
        {
            for (int i = sr.content.childCount; i >=1; i--)
            {
                float curDist = -(i - 1) * (rectTr.sizeDelta.x + sr.content.GetComponent<HorizontalLayoutGroup>().spacing);
                float abs = Mathf.Abs(localPosContenNeedTo - curDist);
                if (abs < rectTr.sizeDelta.x)
                {
                    centerValue = curDist;
                    break;
                }
            }
            float rightMax = -(sr.content.transform.childCount - 1) * (rectTr.sizeDelta.x + sr.content.GetComponent<HorizontalLayoutGroup>().spacing);
            localPosContenNeedTo = Mathf.Max(rightMax, localPosContenNeedTo);
        }
        progress = 0;

   
    }

    void Update()
    {
        progress += Time.deltaTime*8f;
        if (progress < 1.01f)
        {
            RectTransform rectContent = sr.content.GetComponent<RectTransform>();
            Vector2 posCent = new Vector2(centerValue, 0);
            rectContent.anchoredPosition = Vector2.Lerp(rectContent.anchoredPosition, posCent, progress);
        }
    }
}
